package validjson;

public class NumberValidator implements Validator {
    private Schema schema;

    public NumberValidator(Schema schema) {
        this.schema = schema;
    }

    public void validate(Object jsonToValidate) throws ValidationException {
        if (!(jsonToValidate instanceof Number)) {
            throw new ValidationException(String.format("Validator expected a value of type '%s' but got %s", "Number", jsonToValidate == null ? null : jsonToValidate.getClass()));
        }

        Number number = (Number)jsonToValidate;

        if (schema.containsKey("maximum")) {
            boolean maximumCanEqual = schema.containsKey("maximumCanEqual") ? (Boolean)schema.getValue("maximumCanEqual") : true;
            Number maximum = (Number) schema.getValue("maximum");
            if (number.doubleValue() > maximum.doubleValue() || (!maximumCanEqual && number.doubleValue() == maximum.doubleValue())) {
                throw new ValidationException("Value '" + number + "' must be <" + (maximumCanEqual ? "=" : "") + " " + maximum);
            }
        }

        if (schema.containsKey("minimum")) {
            boolean minimumCanEqual = schema.containsKey("minimumCanEqual") ? (Boolean)schema.getValue("minimumCanEqual") : true;
            Number minimum = (Number) schema.getValue("minimum");
            if (number.doubleValue() < minimum.doubleValue() || (!minimumCanEqual && number.doubleValue() == minimum.doubleValue())) {
                throw new ValidationException("Value '" + number + "' must be >" + (minimumCanEqual ? "=" : "") + " " + minimum);
            }
        }
    }
}
